/**
 * 支付功能API路由
 */
import express, { type Request, type Response } from 'express';

const router = express.Router();

// 订单接口类型定义
interface Order {
  id: string;
  userId: string;
  type: 'product' | 'consultation' | 'membership';
  items: OrderItem[];
  totalAmount: number;
  discountAmount?: number;
  finalAmount: number;
  status: 'pending' | 'paid' | 'cancelled' | 'refunded';
  paymentMethod?: 'wechat' | 'alipay' | 'apple_pay';
  paymentId?: string;
  shippingAddress?: ShippingAddress;
  createdAt: string;
  paidAt?: string;
  cancelledAt?: string;
}

interface OrderItem {
  id: string;
  productId?: string;
  consultationId?: string;
  membershipId?: string;
  name: string;
  price: number;
  quantity: number;
  specifications?: Record<string, string>;
}

interface ShippingAddress {
  name: string;
  phone: string;
  province: string;
  city: string;
  district: string;
  address: string;
  isDefault?: boolean;
}

interface PaymentResult {
  success: boolean;
  orderId: string;
  paymentId?: string;
  paymentUrl?: string;
  qrCode?: string;
  message?: string;
}

interface Coupon {
  id: string;
  name: string;
  type: 'discount' | 'amount' | 'shipping';
  value: number; // 折扣百分比或减免金额
  minAmount?: number; // 最低消费金额
  maxDiscount?: number; // 最大优惠金额
  validFrom: string;
  validTo: string;
  usageLimit: number;
  usedCount: number;
  isActive: boolean;
}

// 模拟数据存储
let orders: Order[] = [];
let coupons: Coupon[] = [
  {
    id: 'coupon1',
    name: '新用户专享券',
    type: 'amount',
    value: 20,
    minAmount: 100,
    validFrom: '2024-01-01T00:00:00Z',
    validTo: '2024-12-31T23:59:59Z',
    usageLimit: 1000,
    usedCount: 156,
    isActive: true
  },
  {
    id: 'coupon2',
    name: '满200减50',
    type: 'amount',
    value: 50,
    minAmount: 200,
    validFrom: '2024-01-01T00:00:00Z',
    validTo: '2024-06-30T23:59:59Z',
    usageLimit: 500,
    usedCount: 89,
    isActive: true
  },
  {
    id: 'coupon3',
    name: '9折优惠券',
    type: 'discount',
    value: 10, // 10% 折扣
    minAmount: 50,
    maxDiscount: 100,
    validFrom: '2024-01-01T00:00:00Z',
    validTo: '2024-12-31T23:59:59Z',
    usageLimit: 2000,
    usedCount: 567,
    isActive: true
  }
];

/**
 * 创建订单
 * POST /api/payment/orders
 */
router.post('/orders', (req: Request, res: Response) => {
  try {
    const {
      userId,
      type,
      items,
      couponId,
      shippingAddress
    } = req.body;
    
    if (!userId || !type || !items || items.length === 0) {
      return res.status(400).json({
        success: false,
        error: '用户ID、订单类型和商品项为必填项'
      });
    }
    
    // 计算总金额
    const totalAmount = items.reduce((sum: number, item: OrderItem) => {
      return sum + (item.price * item.quantity);
    }, 0);
    
    let discountAmount = 0;
    
    // 应用优惠券
    if (couponId) {
      const coupon = coupons.find(c => c.id === couponId && c.isActive);
      if (coupon && totalAmount >= (coupon.minAmount || 0)) {
        if (coupon.type === 'amount') {
          discountAmount = coupon.value;
        } else if (coupon.type === 'discount') {
          discountAmount = Math.min(
            totalAmount * (coupon.value / 100),
            coupon.maxDiscount || totalAmount
          );
        }
      }
    }
    
    const finalAmount = Math.max(0, totalAmount - discountAmount);
    
    const newOrder: Order = {
      id: 'order_' + Date.now(),
      userId,
      type,
      items,
      totalAmount,
      discountAmount,
      finalAmount,
      status: 'pending',
      shippingAddress,
      createdAt: new Date().toISOString()
    };
    
    orders.push(newOrder);
    
    res.status(201).json({
      success: true,
      data: newOrder
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '创建订单失败'
    });
  }
});

/**
 * 发起支付
 * POST /api/payment/pay
 */
router.post('/pay', (req: Request, res: Response) => {
  try {
    const { orderId, paymentMethod } = req.body;
    
    if (!orderId || !paymentMethod) {
      return res.status(400).json({
        success: false,
        error: '订单ID和支付方式为必填项'
      });
    }
    
    const orderIndex = orders.findIndex(o => o.id === orderId);
    if (orderIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      });
    }
    
    if (orders[orderIndex].status !== 'pending') {
      return res.status(400).json({
        success: false,
        error: '订单状态不允许支付'
      });
    }
    
    // 模拟支付处理
    const paymentId = 'pay_' + Date.now();
    
    // 更新订单状态
    orders[orderIndex].paymentMethod = paymentMethod;
    orders[orderIndex].paymentId = paymentId;
    
    // 模拟不同支付方式的响应
    let paymentResult: PaymentResult;
    
    switch (paymentMethod) {
      case 'wechat':
        paymentResult = {
          success: true,
          orderId,
          paymentId,
          qrCode: `https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=wechat%20pay%20qr%20code&image_size=square`,
          message: '请使用微信扫码支付'
        };
        break;
      case 'alipay':
        paymentResult = {
          success: true,
          orderId,
          paymentId,
          paymentUrl: `https://example.com/alipay/redirect?paymentId=${paymentId}`,
          message: '正在跳转到支付宝支付页面'
        };
        break;
      case 'apple_pay':
        paymentResult = {
          success: true,
          orderId,
          paymentId,
          message: '请使用Touch ID或Face ID完成支付'
        };
        break;
      default:
        return res.status(400).json({
          success: false,
          error: '不支持的支付方式'
        });
    }
    
    res.json({
      success: true,
      data: paymentResult
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '发起支付失败'
    });
  }
});

/**
 * 支付回调（模拟）
 * POST /api/payment/callback
 */
router.post('/callback', (req: Request, res: Response) => {
  try {
    const { paymentId, status, orderId } = req.body;
    
    const orderIndex = orders.findIndex(o => o.paymentId === paymentId);
    if (orderIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      });
    }
    
    if (status === 'success') {
      orders[orderIndex].status = 'paid';
      orders[orderIndex].paidAt = new Date().toISOString();
    } else {
      orders[orderIndex].status = 'cancelled';
      orders[orderIndex].cancelledAt = new Date().toISOString();
    }
    
    res.json({
      success: true,
      message: '支付状态更新成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '支付回调处理失败'
    });
  }
});

/**
 * 查询支付状态
 * GET /api/payment/status/:orderId
 */
router.get('/status/:orderId', (req: Request, res: Response) => {
  try {
    const { orderId } = req.params;
    
    const order = orders.find(o => o.id === orderId);
    if (!order) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      });
    }
    
    res.json({
      success: true,
      data: {
        orderId: order.id,
        status: order.status,
        paymentMethod: order.paymentMethod,
        finalAmount: order.finalAmount,
        paidAt: order.paidAt
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '查询支付状态失败'
    });
  }
});

/**
 * 获取订单列表
 * GET /api/payment/orders
 */
router.get('/orders', (req: Request, res: Response) => {
  try {
    const { userId, status, page = 1, limit = 10 } = req.query;
    
    let filteredOrders = [...orders];
    
    if (userId) {
      filteredOrders = filteredOrders.filter(o => o.userId === userId);
    }
    
    if (status) {
      filteredOrders = filteredOrders.filter(o => o.status === status);
    }
    
    // 按创建时间倒序
    filteredOrders.sort((a, b) => 
      new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    );
    
    // 分页
    const startIndex = (Number(page) - 1) * Number(limit);
    const endIndex = startIndex + Number(limit);
    const paginatedOrders = filteredOrders.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        list: paginatedOrders,
        total: filteredOrders.length,
        page: Number(page),
        limit: Number(limit),
        hasMore: endIndex < filteredOrders.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取订单列表失败'
    });
  }
});

/**
 * 获取订单详情
 * GET /api/payment/orders/:id
 */
router.get('/orders/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    const order = orders.find(o => o.id === id);
    if (!order) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      });
    }
    
    res.json({
      success: true,
      data: order
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取订单详情失败'
    });
  }
});

/**
 * 取消订单
 * POST /api/payment/orders/:id/cancel
 */
router.post('/orders/:id/cancel', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { userId, reason } = req.body;
    
    const orderIndex = orders.findIndex(o => o.id === id);
    if (orderIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      });
    }
    
    const order = orders[orderIndex];
    
    // 检查权限
    if (order.userId !== userId) {
      return res.status(403).json({
        success: false,
        error: '无权限操作此订单'
      });
    }
    
    // 检查订单状态
    if (order.status !== 'pending') {
      return res.status(400).json({
        success: false,
        error: '订单状态不允许取消'
      });
    }
    
    orders[orderIndex].status = 'cancelled';
    orders[orderIndex].cancelledAt = new Date().toISOString();
    
    res.json({
      success: true,
      message: '订单取消成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '取消订单失败'
    });
  }
});

/**
 * 获取可用优惠券
 * GET /api/payment/coupons
 */
router.get('/coupons', (req: Request, res: Response) => {
  try {
    const { userId, amount } = req.query;
    
    let availableCoupons = coupons.filter(c => c.isActive);
    
    // 根据订单金额筛选可用优惠券
    if (amount) {
      const orderAmount = Number(amount);
      availableCoupons = availableCoupons.filter(c => 
        !c.minAmount || orderAmount >= c.minAmount
      );
    }
    
    // 按优惠力度排序
    availableCoupons.sort((a, b) => {
      const valueA = a.type === 'amount' ? a.value : (Number(amount) || 0) * (a.value / 100);
      const valueB = b.type === 'amount' ? b.value : (Number(amount) || 0) * (b.value / 100);
      return valueB - valueA;
    });
    
    res.json({
      success: true,
      data: availableCoupons
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取优惠券失败'
    });
  }
});

/**
 * 计算优惠券折扣
 * POST /api/payment/calculate-discount
 */
router.post('/calculate-discount', (req: Request, res: Response) => {
  try {
    const { couponId, amount } = req.body;
    
    if (!couponId || !amount) {
      return res.status(400).json({
        success: false,
        error: '优惠券ID和金额为必填项'
      });
    }
    
    const coupon = coupons.find(c => c.id === couponId && c.isActive);
    if (!coupon) {
      return res.status(404).json({
        success: false,
        error: '优惠券不存在或已失效'
      });
    }
    
    const orderAmount = Number(amount);
    
    // 检查最低消费金额
    if (coupon.minAmount && orderAmount < coupon.minAmount) {
      return res.status(400).json({
        success: false,
        error: `订单金额需满${coupon.minAmount}元才能使用此优惠券`
      });
    }
    
    let discountAmount = 0;
    
    if (coupon.type === 'amount') {
      discountAmount = coupon.value;
    } else if (coupon.type === 'discount') {
      discountAmount = Math.min(
        orderAmount * (coupon.value / 100),
        coupon.maxDiscount || orderAmount
      );
    }
    
    const finalAmount = Math.max(0, orderAmount - discountAmount);
    
    res.json({
      success: true,
      data: {
        originalAmount: orderAmount,
        discountAmount,
        finalAmount,
        coupon: {
          id: coupon.id,
          name: coupon.name,
          type: coupon.type,
          value: coupon.value
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '计算优惠失败'
    });
  }
});

export default router;